/**
 * Copyright (C) 2010 Antonio Pinho, Carlos Guimarães, Diogo Pinheiro,
 * Diogo Teles, Linda Velte, Luís Bastião
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/*
 * 2010 11 08 - Adapted the public API to calculator example
 *
 *
 */
package org.me.androidresttest;

import android.util.Log;
import java.net.URI;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

/**
 * Wrapper para a chamada de webservices do ParkMe
 *
 * @author Antonio Pinho - 38535
 * @author Carlos Guimaraes - 39155
 * @author Diogo Pinheiro - 39028
 * @author Diogo Teles - 33394
 * @author Linda Velte - 38735
 * @author Luís Bastião - 38323
 */
public class WSCaller {

    private static String NAMESPACE;               // namespace
    private static String URL;                     // url para o webservice
    public static String LOG_TAG = "WSCALLER";

    public static String getSoapAction(String methodName) {
        return NAMESPACE + methodName;
    }

    /**
     * Construtor da classe WSCaller. Permite inicializar a chamada de um método
     * do webService.
     *
     * @param soap_action Soap action do método a ser chamado
     * @param method_name nome do método a ser chamado
     */
    public WSCaller(String namespace, String baseUrl) {
        WSCaller.NAMESPACE = namespace;
        WSCaller.URL = baseUrl;
        Log.d(LOG_TAG, "constructor");
    }

    /**
     * Permite o envio de um request para o webservice e a recepção da respectiva
     * resposta.
     * 
     * @param fieldName identificador dos parametros de entrada.
     * @param fieldValue valores dos parametros de entrada.
     */
    public SoapObject invokeWebService(String methodName, String[] fieldName, String[] fieldValue) {
        Log.d(LOG_TAG, "invoke - starting");
        SoapObject request = new SoapObject(NAMESPACE, methodName);
        Log.d(LOG_TAG, "invoke - namespace = " + NAMESPACE);

        /* Adicionar as propriedades ao pedido. */
        for (int i = 0; i < fieldName.length; ++i) {
            request.addProperty(fieldName[i], fieldValue[i]);
        }

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
        soapEnvelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.debug = true;
        try {
            Log.d(LOG_TAG, "invoke - making call");
            androidHttpTransport.call(getSoapAction(methodName), soapEnvelope);
            Log.d(LOG_TAG, "invoke - call made");
            return (SoapObject) soapEnvelope.bodyIn;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * Chamada e tratamento da resposta do método parkMe do webservice
     *
     * @param latitude latitude da posição do utilizador
     * @param longitude longitude da posição do utilizador
     * @param id identificador do cliente
     * @return lista de parques
     */
    public int add(int a, int b) {

        Log.d(LOG_TAG, "add ");

        SoapObject result = invokeWebService("add",
                new String[]{"a", "b"},
                new String[]{"" + a, "" + b,});


        Log.d(LOG_TAG, "add - process response ");
        int response;

        /* "Desembrulhar" o SOAP object e criar o resultado. */
        if (result != null) {
            String responseWS = "" + result.getProperty("return");
            response = Integer.valueOf(responseWS);
        } else {
            response = -1;
        }

        return response;
    }

    public boolean newUser(String number, String name) {
        SoapObject result = invokeWebService(
                "newUser",
                new String[]{"number", "name"},
                new String[]{number, name});

        boolean response;

        if (result != null) {
            response = Boolean.valueOf(result.getProperty("return").toString());
        } else {
            response = false;
        }

        return response;
    }
    public boolean requestFriendship(String number, String friendNumber) {
        SoapObject result = invokeWebService(
                "requestFriendship",
                new String[]{"number", "friendNumber"},
                new String[]{number, friendNumber});

        boolean response;

        if (result != null) {
            response = Boolean.valueOf(result.getProperty("return").toString());
        } else {
            response = false;
        }
        return response;
    }

    public boolean deleteFriendship(String number, String friendNumber) {
        SoapObject result = invokeWebService(
                "deleteFriendship",
                new String[]{"number", "friendNumber"},
                new String[]{number, friendNumber});

        boolean response;

        if (result != null) {
            response = Boolean.valueOf(result.getProperty("return").toString());
        } else {
            response = false;
        }

        return response;
    }

    public boolean findByNumber(String friendNumber) {
        SoapObject result = invokeWebService(
                "findFriendByNumber",
                new String[]{"friendNumber"},
                new String[]{friendNumber});

        boolean response;

        if (result != null) {
            response = Boolean.valueOf(result.getProperty("return").toString());
        } else {
            response = false;
        }
        return response;
    }
}
